package com.laiqilin.service.impl;

import com.alibaba.fastjson.JSON;
import com.laiqilin.entity.LoginUser;
import com.laiqilin.service.TokenService;
import com.laiqilin.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class TokenServiceImpl implements TokenService {

	@Autowired
	private StringRedisTemplate redisTemplate;

	/**
	 * 创建并返回用户的Token
	 *
	 * @param user 登录用户信息
	 * @return 包含token的Map
	 */
	@Override
	public Map<String, Object> createToken(LoginUser user) {

		// 构建JWT的Claims部分
		Map<String, Object> claims = new HashMap<>();
		String uuid = UUID.randomUUID().toString().replace("-", "");
		claims.put("userId", user.getUserId());
		claims.put("username", user.getUser().getUsername());
		claims.put("user_key", uuid);

		// 生成Token
		String token = JwtUtil.createToken(claims);

		// 返回Token
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("token", token);

		// 将用户信息存储在Redis中，使用UUID作为key
		String key = "login_tokens:" + uuid;
		redisTemplate.opsForValue().set(key, JSON.toJSONString(user), 100, TimeUnit.DAYS);

		return resultMap;
	}
}
